const express = require("express");
let loginRouter = express.Router();
const userModel = require("../models/usersModel");
const adminModel = require("../models/adminModel");
const md5 = require("md5");
const jwt = require("jsonwebtoken");


loginRouter.get("/checkname", async (req, res) => {
    let { username } = req.query;
    try {
        // 接收用户名，查询数据库是否有内容；
        let reslut = await userModel.find({ username });
        reslut = reslut.length==0? await adminModel.find({ username }) : reslut;
        // console.log(reslut);
        
        if (reslut.length > 0) {
            res.json({
                info: "用户名正确",
                status: 1
            })
        } else {
            res.json({
                info: "用户名不正确",
                status: 2
            })
        }
    }catch(err){
        res.json({
            info: "错误",
            status: 0,
            err
        })
    }
})

loginRouter.post("/checkuser", async (req,res)=>{
    let{ username,pwd } = req.body;
    // console.log(username,pwd);
    let reslut = await userModel.find({ username,pwd:md5(pwd) });
    reslut = reslut.length==0? await adminModel.find({ username,pwd:md5(pwd) }) : reslut;

    if (reslut.length > 0) {
        let token = jwt.sign({ myname: "hello" }, "mytoken", { expiresIn: "2h" });

        res.json({
            info: "用户名且密码正确",
            status: 1,
            token
        })
    } else {
        res.json({
            info: "用户名或者密码错误",
            status: 2
        })
    }
})

module.exports = loginRouter;